LINQ to XML - Queries That Preserve Hierarchy


LINQ, LINQ to XML, .NET Framework 4.0
LINQ, LINQ to XML, XML, Console Window, XML Documentation
Desktop, Data
en-US
6/28/2011

Introduction

These samples demonstrate how to output data into a new XML file structure while preserving the overall data and hierarchy.

Building the Sample

Are there special requirements or instructions for building the sample?

Description

How does this sample solve the problem?

You can include code snippets, images, videos.   

 

C#
Edit|Remove
            [Category("TREE - Queries that preserve hierarchy")] 
            [Description(@"Prepare a (nested) table of contents for Book1, listing all the sections and their titles. Preserve the original attributes of each <section> element, if any.")] 
            public void Q13() 
            { 
                XDocument book = XDocument.Load("book.xml"); 
 
                var result = new XElement("toc", 
                                 TableOfContents(book.Element("book"))); 
 
                Console.WriteLine(result); 
 
                // Solution in XQuery: 
                // declare function local:toc($book-or-section as element()) as element()* 
                // { 
                //    for $section in $book-or-section/section 
                //    return 
                //    <section> 
                //        { $section/@* , $section/title , local:toc($section) }                  
                //    </section> 
                // }; 
                // <toc> 
                // { 
                //    for $s in doc(""book.xml"")/book return local:toc($s) 
                // } 
                // </toc> 
            }

Source Code Files

More Information

For more information on LINQ to XML: http://msdn.microsoft.com/en-us/library/bb387098.aspx